package handler

import (
	"cargo-perm-mgr/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

func UserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
}
func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
}
func UsersRoles(c *gin.Context) {
	/*
		SELECT
			*
			FROM
			roles
			LEFT JOIN user_roles on user_roles.rid=roles.id
			WHERE user_roles.uid=1
	*/
	rid, _ := strconv.Atoi(c.Query("rid"))

	var usersroles model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles on user_roles.rid=roles.id").
		Where("user_roles.uid=?", rid).
		Debug().Find(&usersroles)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  usersroles,
		"data": "success",
	})
}

func RolesNodes(c *gin.Context) {
	/*
		SELECT
		*
		FROM
		nodes
		LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE role_nodes.rid=1
	*/
	nid, _ := strconv.Atoi(c.Query("nid"))
	var rolesNodes model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid=?", nid).
		Debug().Find(&rolesNodes)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  rolesNodes,
		"data": "success",
	})
}
